#include "HttpServer.hpp"
#include <memory>

using namespace server;
using namespace std;

static void Usage(string proc)
{
    cout << "\nUsage:\n\t" << proc << "  local port\n\n";
}

std::string suffixToDesc(const std::string suffix)
{
    std::string ct = "Content-Type: ";
    if (suffix == ".html")
        ct += "test/html";
    else if (suffix == ".jpg")
        ct += "application/x-jpg";
    ct += "\r\n";
    return ct;
}

// 1.服务器和网页分离，html
// 2.url -> / : web根目录
// 3.我们要正确的给客户端返回资源类型，我们首先要自己知道！所以的资源都有后缀！！
bool Get(const HttpRequest &req, HttpResponse &resp)
{
    // for test
    cout << "-----------------------http start-----------------------------" << endl;
    cout << req.inbuffer << std::endl;
    std::cout << "method: " << req.method << std::endl;
    std::cout << "url: " << req.url << std::endl;
    std::cout << "httpversion: " << req.httpversion << std::endl;
    std::cout << "path: " << req.path << std::endl;
    std::cout << "suffix: " << req.suffix << std::endl;
    std::cout << "size: " << req.size << "字节" << std::endl;
    cout << "-----------------------http end-------------------------------" << endl;

    string respline = "HTTP/1.1 200 OK\r\n";
    // string respheader = "Context-Type: text/html\r\n";
    string respheader = suffixToDesc(req.suffix);
    if (req.size > 0)
    {
        respheader += "Context-Length: ";
        respheader += std::to_string(req.size);
        respheader += "\r\n";
    }
    string respblank = "\r\n";

    // string body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>6666.test</title><h1>你是大宝吗？？</h1></head><body><p>彩萍是大宝</p></body></html>";

    std::string body;
    if (!Util::readFile(req.path, &body))
    {
        Util::readFile(html_404, &body); // 一定能成功
    }

    resp.outbuffer += respline;
    resp.outbuffer += respheader;
    resp.outbuffer += respblank;
    resp.outbuffer += body;
    cout << "-----------------------http response start-----------------------------" << endl;
    std::cout << resp.outbuffer << std::endl;
    cout << "-----------------------http response start-----------------------------" << endl;

    return true;
}

// ./tcpServer local_port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t port = atoi(argv[1]);
    // string ip = argv[1];
    std::unique_ptr<HttpServer> httpser(new HttpServer(Get, port));

    httpser->initServer();
    httpser->start();
    return 0;
}